import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import router from "../router";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: null,
    userInfo: null,
    permissions: new Set(),
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    userRole: (state) => state.userInfo?.role,
    hasPermission: (state) => (permission) => state.permissions.has(permission),
  },
  actions: {
    setToken(token) {
      this.token = token;
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      this.setupPermissions(userInfo.role);
    },
    setupPermissions(role) {
      this.permissions.clear();
      switch (role) {
        case 0: // 超级管理员
          this.permissions.add("admin:all");
          break;
        case 1: // 管理员
          this.permissions.add("admin:manage");
          this.permissions.add("product:all");
          this.permissions.add("order:all");
          this.permissions.add("user:view");
          this.permissions.add("user:edit");
          this.permissions.add("community:manage"); // 添加社区管理权限
          break;
        case 2: // 主管
          this.permissions.add("employee:manage");
          this.permissions.add("product:all");
          this.permissions.add("community:manage"); // 添加社区管理权限
          break;
        case 3: // 员工
          this.permissions.add("product:edit");
          this.permissions.add("product:own");
          this.permissions.add("community:view"); // 添加社区查看权限
          break;
        case 4: // 老师
          this.permissions.add("course:manage");
          this.permissions.add("community:view"); // 添加社区查看权限
          break;
      }
    },
    // 检查是否有多个权限中的任意一个
    hasAnyPermission(permissions) {
      if (!permissions || permissions.length === 0) return true;
      return permissions.some(permission => this.permissions.has(permission));
    },
    logout() {
      // 清除token
      this.token = null;
      this.userInfo = null;
      this.permissions.clear();
      // 清除本地存储
      localStorage.removeItem("user");
      // 显示退出成功提示
      ElMessage.success("已安全退出系统");
      // 跳转到登录页
      router.push("/login");
    },
    checkTokenExpiration() {
      if (!this.token) return;
      try {
        const payload = JSON.parse(atob(this.token.split(".")[1]));
        if (Date.now() >= payload.exp * 1000) {
          ElMessage.error("登录已过期，请重新登录");
          this.logout();
        }
      } catch (error) {
        console.error("Token验证失败:", error);
        this.logout();
      }
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "user",
        storage: localStorage,
        paths: ["token", "userInfo"],
      },
    ],
  },
});